package com.binance.notification.web.push;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.binance.master.utils.JsonUtils;
import com.google.common.collect.Lists;
import com.google.gson.annotations.Expose;

import cn.jiguang.common.resp.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PushResult extends cn.jpush.api.push.PushResult {

    private static final long serialVersionUID = 6142139293612374139L;

    @Expose
    private List<PushResult> pushErrResultList;
    private Exception ex;

    /**
     * 本次请求时正常返回
     */
    @Override
    public boolean isResultOK() {
        if (this.ex != null) {
            return false;
        }
        return super.isResultOK();
    }

    public Exception getEx() {
        return ex;
    }

    public void setEx(Exception ex) {
        this.ex = ex;
    }

    public Iterator<PushResult> errIterator() {
        if (this.pushErrResultList == null) {
            return new ArrayList<PushResult>().iterator();
        }
        return pushErrResultList.iterator();
    }

    /**
     * 如果推送上下文中明确设置了不需要返回结果，则返回Null
     * 
     * @param responseWrapper
     * @return
     */
    public static PushResult fromResponse(ResponseWrapper responseWrapper) {
        if (!JClient.needPushResult()) {// 此处的作用是为了再不需要返回值的时候不再解析返回内容，从而加快处理速度，提供些许性能
            log.info("推送消息到极光私有云返回结果：{}", responseWrapper);
            return null;
        }
        PushResult result = new PushResult();
        result.setResponseWrapper(responseWrapper);
        result.pushErrResultList = Lists.newArrayList();
        if (responseWrapper.isServerResponse()) {
            if (StringUtils.isNotBlank(responseWrapper.responseContent)) {
                try {
                    result.pushErrResultList.add(_gson.fromJson(responseWrapper.responseContent, PushResult.class));
                } catch (Exception e) {
                    result.pushErrResultList = JsonUtils.toObjList(responseWrapper.responseContent, PushResult.class);
                }
            }
        }
        log.info("推送消息到极光私有云返回结果：{}", result);
        return result;
    }

}
